package com.seantone.inappupdate.plugin.xiaomi;

import android.app.Activity;
import android.content.Context;

import com.seantone.inappupdate.activity.UpdateType12Activity;
import com.seantone.inappupdate.core.define.CheckUpdateParams;
import com.seantone.inappupdate.core.define.CheckUpdateRet;
import com.seantone.inappupdate.core.impl.ICheckUpdateCallBack;
import com.seantone.inappupdate.core.impl.IInAppUpdate;
import com.seantone.inappupdate.core.impl.IRequestUpdate;

import com.seantone.inappupdate.core.utils.OAIDRom;
import com.seantone.inappupdate.core.utils.Utils;
import com.xiaomi.market.sdk.Log;
import com.xiaomi.market.sdk.UpdateResponse;
import com.xiaomi.market.sdk.UpdateStatus;
import com.xiaomi.market.sdk.XiaomiUpdateAgent;
import com.xiaomi.market.sdk.XiaomiUpdateListener;

public class SDK implements IInAppUpdate {
    @Override
    public boolean isBest(Context context) {
        return OAIDRom.isXiaomi() &&  Utils.verifyInstallerId(context, "com.xiaomi.market");
    }

    @Override
    public boolean isSupport(Context context) {
        // 非miui也是支持的
        return true;
    }

    @Override
    public void checkUpdate(Context context, CheckUpdateParams params, ICheckUpdateCallBack callBack) {
        XiaomiUpdateAgent.setUpdateAutoPopup(false);
        XiaomiUpdateAgent.update(context, false);


            XiaomiUpdateAgent.setUpdateListener((i, updateResponse) -> {
                CheckUpdateRet ret = new CheckUpdateRet();
                ret.versionName = updateResponse.versionName;
                ret.versionCode = updateResponse.versionCode;
                ret.updateLog = updateResponse.updateLog ;
                callBack.onRet(ret);

                if(params.auto){
                    ((Activity)context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UpdateType12Activity.launch(context,ret);
                        }
                    });

                }
            });

    }

    @Override
    public void requestUpdate(Context context, IRequestUpdate callBack) {
        XiaomiUpdateAgent.arrange();
    }
}
